// https://leetcode.cn/problems/island-perimeter/

class Solution {
private:
    int area;
    int dirs[4][2] = {{0, 1}, {0, -1}, {1 ,0}, {-1, 0}};
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        area = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    dfs(grid, visited, i, j, m, n);
                    break;
                }
            }
        }
        return area;
    }

    void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y, int m, int n) {
        if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0) {
            area++;
            return;
        }

        if (visited[x][y]) {
            return;
        }

        visited[x][y] = true;
        for (auto dir : dirs) {
            dfs(grid, visited, x + dir[0], y + dir[1], m, n);
        }
    }
};